package com.qst.crop.controller;

import com.qst.crop.common.Result;
import com.qst.crop.common.StatusCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class FilesUploadController {

    @Value("${application.upload-path}")
    private String uploadRootPath;

    private static final DateTimeFormatter TS_FMT = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    @PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file) throws IOException {
        return saveFile(file, "avatar");
    }

    @PostMapping(value = "/material", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<String> uploadMaterial(@RequestParam("file") MultipartFile file) throws IOException {
        return saveFile(file, "order");
    }

    private Result<String> saveFile(MultipartFile file, String subDir) throws IOException {
        if (file == null || file.isEmpty()) {
            return new Result<String>(false, StatusCode.ERROR, "文件为空", null);
        }

        String originalFilename = file.getOriginalFilename();
        String ext = "";
        if (StringUtils.hasText(originalFilename) && originalFilename.lastIndexOf('.') > -1) {
            ext = originalFilename.substring(originalFilename.lastIndexOf('.'));
        }

        String datePart = LocalDateTime.now().format(TS_FMT);
        String newFileName = datePart + "_" + UUID.randomUUID().toString().replace("-", "") + ext;

        File dir = new File(uploadRootPath + File.separator + subDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String targetFileName = dir.getAbsolutePath() + File.separator + newFileName;
        File targetFile = new File(targetFileName);
        file.transferTo(targetFile);

        String url = "/file/" + subDir + "/" + newFileName;
        return new Result<String>(true, StatusCode.OK, "上传成功", url);
    }
}


